package thread;

public class 线程变量可见性 {


    /**
     * 每个线程都有独立的内存空间，运行时会拷贝主存变量存为线程副本变量
     * @param args
     * @throws InterruptedException
     */

    public static void main(String[] args) throws InterruptedException {

        MyService myService=new MyService();
        ThreadA a=new ThreadA(myService);
        ThreadB b=new ThreadB(myService);
        a.start();
        Thread.sleep(1000);
        b.start();
        Thread.sleep(1000);
        myService.print();

    }


}
class MyService{

    private  Boolean isContinueRun=true;

    public void print(){
        System.out.println(isContinueRun);
    }

    public void runMethod(){
        System.out.println("runHash="+isContinueRun.hashCode());
        while (isContinueRun==true){

        }
        System.out.println("停止啦");
    }

    public void stopMethod(){
        System.out.println("stopMethod="+isContinueRun.hashCode());
        this.isContinueRun=false;
    }

}


class ThreadA extends Thread{

  volatile   MyService myService;

    ThreadA(MyService myService){
        this.myService=myService;
    }

    public void run(){
        myService.runMethod();
    }
}
class ThreadB extends Thread{

    MyService myService;

    ThreadB(MyService myService){
        this.myService=myService;
    }

    public void run(){
        System.out.println("设置停止变量");
        myService.stopMethod();
    }
}